package xin.ryven.car.android.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView

class BlurView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    private var blurredBitmap: Bitmap? = null
    private val paint = Paint()
    private val matrix = Matrix()

    init {
        scaleType = ScaleType.CENTER_CROP
        alpha = 0.3f  // 增加透明度，让背景更清晰一些
    }

    override fun setImageBitmap(bitmap: Bitmap?) {
        bitmap?.let {
            try {
                // 创建一个新的位图用于模糊处理
                val scaledBitmap = scaleBitmap(it)
                blurredBitmap = createBlurredBitmap(scaledBitmap)
                scaledBitmap.recycle()
                
                // 不调用父类的setImageBitmap，而是触发重绘
                invalidate()
            } catch (e: Exception) {
                // 如果模糊处理失败，使用原图
                super.setImageBitmap(it)
            }
        }
    }

    private fun scaleBitmap(source: Bitmap): Bitmap {
        // 增大缩放因子，保留更多细节
        val scaleFactor = 0.4f
        val width = (source.width * scaleFactor).toInt()
        val height = (source.height * scaleFactor).toInt()
        return Bitmap.createScaledBitmap(source, width, height, true)
    }

    private fun createBlurredBitmap(source: Bitmap): Bitmap {
        val renderScript = RenderScript.create(context)
        val input = Allocation.createFromBitmap(renderScript, source)
        val output = Allocation.createTyped(renderScript, input.type)
        val blur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript))
        
        blur.setInput(input)
        blur.setRadius(15f)  // 降低模糊半径，使图片轮廓更清晰
        blur.forEach(output)
        
        val blurred = Bitmap.createBitmap(source.width, source.height, source.config)
        output.copyTo(blurred)
        
        renderScript.destroy()
        return blurred
    }

    override fun onDraw(canvas: Canvas) {
        blurredBitmap?.let { bitmap ->
            // 计算缩放比例以填充整个视图
            val scale = calculateScale(bitmap)
            matrix.reset()
            matrix.setScale(scale, scale)
            
            // 居中显示
            val dx = (width - bitmap.width * scale) / 2
            val dy = (height - bitmap.height * scale) / 2
            matrix.postTranslate(dx, dy)
            
            canvas.drawBitmap(bitmap, matrix, paint)
        }
    }

    private fun calculateScale(bitmap: Bitmap): Float {
        val widthScale = width.toFloat() / bitmap.width
        val heightScale = height.toFloat() / bitmap.height
        return maxOf(widthScale, heightScale)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        // 清理位图资源
        blurredBitmap?.recycle()
        blurredBitmap = null
    }
} 